﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using System.EnterpriseServices.CompensatingResourceManager;

[assembly: ApplicationCrmEnabled]
[assembly: ApplicationActivation(ActivationOption.Server)]
[assembly: ApplicationAccessControl(AccessChecksLevel=AccessChecksLevelOption.Application,Authentication=AuthenticationOption.None, ImpersonationLevel=ImpersonationLevelOption.Impersonate)]

namespace Reflexive.IO.Transactions
{

    // Create class derived from Compensator class.
    [JustInTimeActivation]
    [Guid("99149EBB-9915-4BC4-B1BF-87E27DCF1F33")]
    public class CompensatingResourceManager : Compensator
    {

        bool bBeginPrepareCalled = false;
        bool bPrepareRecordCalled = false;
        bool bBeginCommitCalled = false;
        bool bCommitRecordCalled = false;
        bool bBeginAbortCalled = false;
        bool bAbortRecordCalled = false;

        String _fileName;

        public override void BeginPrepare()
        {
            bBeginPrepareCalled = true;
        }

        public override bool PrepareRecord(LogRecord rec)
        {
            Object o = rec.Record;
            _fileName = o.ToString();
            bPrepareRecordCalled = true;
            return false;
        }

        public override bool EndPrepare()
        {
            if (!bBeginPrepareCalled)
            { return false; }
            if (!bPrepareRecordCalled)
            { return false; }
            if (_fileName == null)
            { return false; }
            // This is a Prepare Phase success.
            return true;
        }

        public override void BeginCommit(bool fRecovery)
        {
            bBeginCommitCalled = true;
        }

        public override bool CommitRecord(LogRecord rec)
        {
            bCommitRecordCalled = true;
            return true;
        }

        public override void EndCommit()
        {
            if (!bBeginCommitCalled)
            { return; }
            if (!bCommitRecordCalled)
            { return; }
            if (_fileName == null)
            { return; }
            // This is a Commit Phase success.
        }

        public override void BeginAbort(bool fRecovery)
        {
            bBeginAbortCalled = true;
        }

        public override bool AbortRecord(LogRecord rec)
        {
            bAbortRecordCalled = true;
            Object o = rec.Record;
            _fileName = o.ToString();
            return true;
        }

        public override void EndAbort()
        {
            if (!bBeginAbortCalled)
            { return; }
            if (!bAbortRecordCalled)
            { return; }
            if (_fileName == null)
            { return; }
            // This is an Abort Phase success.
        }
    }
}
